package cn.xuqiudong.common.blog.service;

import cn.xuqiudong.common.base.service.BaseService;
import cn.xuqiudong.common.blog.mapper.BlogArticleFileMapper;
import cn.xuqiudong.common.blog.model.BlogArticleFile;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

/**
 * @author Vic.xu
 * 描述:博文按年月归档 Service
 * @since  2020-07-10 11:15
 */
@Service
public class BlogArticleFileService extends BaseService<BlogArticleFileMapper, BlogArticleFile> {

    @Override
    protected boolean hasAttachment() {
        return false;
    }



    /*
    使用这一句初始化了数据 后面应该写个定时器 每月定时统计
    INSERT INTO blog_article_file(num, YEAR, MONTH)
    SELECT t.num, SUBSTRING_INDEX(t.d,'-',1),SUBSTRING_INDEX(t.d,'-',-1)   FROM ((SELECT DATE_FORMAT(a.`create_time`, '%Y-%m') AS d, COUNT(*) AS num
    FROM blog_article a
    GROUP BY d))t
     */

    /**
     * 用于统计的归档定时器<br />
     * <ul>
     *     <li>1. 如果当前表为没有数据 则统计出全部的数据插入当前表</li>
     *     <li>2. 统计当月的归档数据</li>
     * </ul>
     */
    public void statisticsJob() {
        //插叙出表中最后一条的数据
        BlogArticleFile last = mapper.findLast();
        // 1 没有数据  则插入全部
        if (last == null) {
            mapper.statisticsAll();
            return;
        }
        // 判断当月数据是否已经统计过
        LocalDateTime current = LocalDateTime.now();
        boolean counted = last.getMonth() == current.getMonthValue() && last.getYear() == current.getYear();

        LocalDateTime firstDayOfMonth = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        Date lastDate = Date.from(firstDayOfMonth.atZone(ZoneId.systemDefault()).toInstant());
        //统计某个时间之后的数量
        int num = mapper.statisticsNumAfterDate(lastDate);
        //修改为：如果当月没有文章 则不新建记录
        if (num <= 0) {
            return;
        }
        //已经统计 则更新 未统计 则新增
        if (!counted) {
            last = new BlogArticleFile();
            last.setMonth(current.getMonthValue());
            last.setYear(current.getYear());
        }
        last.setNum(num);
        save(last);
    }

    public static void main(String[] args) {

        LocalDateTime time = LocalDateTime.now();
        LocalDateTime firstday = time.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        Date date = Date.from(firstday.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));

    }

}
